package com.lingshi.shopping_seckill_customer_api.controller;

import com.lingshi.shopping.entity.Orders;
import com.lingshi.shopping.entity.SeckillGoods;
import com.lingshi.shopping.result.BaseResult;
import com.lingshi.shopping.service.OrdersService;
import com.lingshi.shopping.service.SecKillService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * 秒杀商品管理
 */
@RestController
@RequestMapping("/user/seckillGoods")
public class SecKillGoodsController {

    @DubboReference
    private SecKillService secKillService;

    @DubboReference
    private OrdersService ordersService;

    /**
     * 分页查询秒杀商品
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/findPage")
    public BaseResult findPage(@RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer size) {
        return BaseResult.success(secKillService.findPageByRedis(page, size));
    }

    /**
     * 根据id查询秒杀商品详情
     * @param id 秒杀商品id
     * @return
     */
    @GetMapping("/findById")
    public BaseResult findById(String id) {

        SeckillGoods seckillGoods = secKillService.findSeckillGoodsByRedis(id);

        if (Objects.isNull(seckillGoods)) {
            seckillGoods = secKillService.findSeckillGoodsByMySQL(id);
        }

        return BaseResult.success(seckillGoods);
    }

    /**
     * 创建秒杀订单
     * @param orders 订单数据
     * @return
     */
    @PostMapping("/add")
    public BaseResult add(@RequestBody Orders orders,@RequestHeader("userId") Long userId) {
        orders.setUserId(userId);
        return BaseResult.success(secKillService.createOrder(orders));
    }

    /**
     * 根据订单id查询订单详情
     * @param id 订单详情
     * @return
     */
    @GetMapping("/findOrder")
    public BaseResult findOrder(String id) {
        return BaseResult.success(secKillService.findOrder(id));
    }

    /**
     * 支付成功以后同步订单到数据库
     * @param id 订单id
     * @return
     */
    @GetMapping("/pay")
    public BaseResult pay(String id) {
        //从redis获取订单
        Orders orders = secKillService.findOrder(id);

        //新增订单到数据库
        ordersService.add(orders);
        return BaseResult.success();
    }

}
